/*
 * @Author: your name
 * @Date: 2020-05-12 17:05:16
 * @LastEditTime: 2020-08-05 16:46:18
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \stroage_server\platform\av_play\av_play.c
 */

#include "query_info.h"
#include "xeSqlite.h"
#include "file_space.h"
#include "userMgntApi.h"
typedef enum _http_query_type{
    E_QUERY_UNKNOW = 0,
    E_QUERY_IPCLIST = 1,
    E_QUERY_FILELIST = 2,
}e_http_query_type;
typedef struct _playInfo{
    char          sid[HISOME_LEN_128];  
    char          ipc_SN[HISOME_LEN_128];
    char          ipc_MAC[HISOME_LEN_128];
    char          opt_type[HISOME_LEN_16];

    char          _startTime[HISOME_LEN_128];
    char          _endTime[HISOME_LEN_128];

}t_queryinfo;


int query_http_respond(MyHttpPack* req,int get_fail,
    char *errReason,  t_queryinfo *p_queryinfo,vector_t *p_vector)
{
    cJSON *rsp,*rspHeader,*rspArr,*rspData;
    rsp=cJSON_CreateArray();
    rspHeader = cJSON_CreateObject();
    rspData = cJSON_CreateObject();

    cJSON_AddStringToObject(rspHeader,"method","QUERY");
    cJSON_AddStringToObject(rspHeader,"SID", p_queryinfo->sid);
    cJSON_AddItemToObject(rspHeader, "data", rspArr=cJSON_CreateArray());
    cJSON_AddItemToArray(rsp,rspHeader);

    if(get_fail){
        cJSON_AddStringToObject(rspHeader,"result","FAIL");
        cJSON_AddStringToObject(rspData,"reason",errReason);
        cJSON_AddItemToArray(rspArr,rspData);
    }else{
        cJSON_AddStringToObject(rspHeader,"result","SUCCESS");

	    if (!strcmp(p_queryinfo->opt_type, "filelist")){
            vector_iter iter;
            vector_t *c = p_vector;

            cJSON_AddStringToObject(rspHeader,"SN", p_queryinfo->ipc_SN);
            c->tmp_cursor = 0;
            for (iter = vector_begin(c); iter != vector_end(c); iter = vector_next(c)) {
                cJSON *record =cJSON_CreateObject();
                char file_name[64]="";
                char tmp_buf[64]="";
                t_file_opt_info *tt = vector_iter_valuep(c, iter, t_file_opt_info);
                get_file_name(tt->file_des.file_name,file_name);
                // xeLOG_DEBUG("vector--> file_name:%s\n",file_name);
                cJSON_AddStringToObject(record,"filename", file_name);
                snprintf(tmp_buf,sizeof(tmp_buf)-1,"%lld",tt->file_des.file_size);
                cJSON_AddStringToObject(record,"filesize",tmp_buf);
                cJSON_AddStringToObject(record,"starttime",
                    com_localTimeInt2Str(tt->file_des.start_time,tmp_buf));
                cJSON_AddStringToObject(record,"endtime",
                    com_localTimeInt2Str(tt->file_des.end_time,tmp_buf));
                cJSON_AddItemToArray(rspArr,record);
            }
        }else if(!strcmp(p_queryinfo->opt_type, "ipclist")){
            vector_iter iter;
            vector_t *c = p_vector;
            c->tmp_cursor = 0;
            for (iter = vector_begin(c); iter != vector_end(c); iter = vector_next(c)) {
                cJSON *record =cJSON_CreateObject();
                char time[128];
                t_ipc_query_info *tt = vector_iter_valuep(c, iter, t_ipc_query_info);
                // xeLOG_DEBUG("vector--> sn:%s\n",tt->ipc_sn);
                cJSON_AddStringToObject(record,"sn", tt->ipc_sn);
                cJSON_AddStringToObject(record,"ipc_name", tt->ipc_name);
                cJSON_AddStringToObject(record,"starttime",
                    com_localTimeInt2Str(tt->start_time,time));
                cJSON_AddStringToObject(record,"endtime",
                    com_localTimeInt2Str(tt->end_time,time));
                cJSON_AddItemToArray(rspArr,record);
            }
        }else{
        }
    }

    com_httpPack(req->httpReq.nc,rsp);
    cJSON_Delete(rsp);

    return 0;
}


void query_info_setup(void *data)
{
    int ret;
    int ret_flag = 0;
    e_http_query_type query_type = E_QUERY_UNKNOW;
    char errReason[HISOME_LEN_512]={'\0'};
    t_queryinfo queryinfo ={0};
    MyHttpPack* req =(MyHttpPack*)data; 
    cJSON *root;
    t_ipc_query_info ipc_info_temp= {0};
    t_ipc_query_result query_result_temp = {0};
    t_ipc_query_info *ipc_info = &ipc_info_temp;
    t_ipc_query_result *p_query_result = &query_result_temp;

    char collector_sn[64]="";
    vector_t *g_vector = NULL;

    STD_print("query_info_setup in");
    root=cJSON_Parse(req->httpReq.hm->body.p);
    if (!root) {
        sprintf(errReason,"客户端发送数据有误");
        ret_flag=1;
        PRTLOG_ERR("Error before: [%s]",cJSON_GetErrorPtr());
        goto query_exit;
    }else{
        char value[HISOME_LEN_256];
        int userid = 0;
        __prase_cjson_string(value,ret_flag,"userID",query_exit);
        sscanf(value,"%d",&userid);
        if(NULL ==apiUsrMgnt_findOn_LINEUser(userid)){
            xeLOG_ERR("error, %d not online",userid);
            ret_flag = 1;
            sprintf(errReason,"error, %d not online",userid);
            goto query_exit;
        }
        __prase_cjson_string(value,ret_flag,"SID",query_exit);
            strcpy(queryinfo.sid,value);
        __prase_cjson_string(value,ret_flag,"opt_type",query_exit);
            strcpy(queryinfo.opt_type,value);

	    if (!strcmp(queryinfo.opt_type, "ipclist")){
            query_type = E_QUERY_IPCLIST;
            memset(value,0,sizeof(value));
            cJSON_GetObjectValue(value,sizeof(value),root,"GTS_SN");
            if(strcmp(value,"")){
                strcpy(collector_sn,value);
            }else{
                xeLOG_NOTICE("collector_sn is NULL");
            }
        }else if (!strcmp(queryinfo.opt_type, "filelist")) {
            __prase_cjson_string(value,ret_flag,"SN",query_exit);
                strcpy(queryinfo.ipc_SN,value);
            __prase_cjson_string(value,ret_flag,"startTime",query_exit);
                strcpy(queryinfo._startTime,value);
            __prase_cjson_string(value,ret_flag,"endTime",query_exit);
                strcpy(queryinfo._endTime,value);
            query_type = E_QUERY_FILELIST;
        }else{
            
        }
    }
    

    /*
     *1 query ipc_sn in sysmgnt.db
     */
    if(query_type == E_QUERY_FILELIST){
        memset(ipc_info, 0 ,sizeof(t_ipc_query_info));
        memset(p_query_result, 0 ,sizeof(t_ipc_query_result));
        p_query_result->p_vector = vector_create(t_file_opt_info);
        g_vector = p_query_result->p_vector;
        __check_return_point(p_query_result->p_vector,ret_flag,"malloc failed",query_exit);

        strcpy(ipc_info->ipc_sn, queryinfo.ipc_SN);
        ipc_info->start_time =  com_localTimeStr2Int(queryinfo._startTime);
        ipc_info->end_time =  com_localTimeStr2Int(queryinfo._endTime);

        tiny_rec_query_sysmgntdb_info(E_TBL_IPCMGNT,(void *)ipc_info);
        __check_return_cstring(ipc_info->storage_path,ret_flag,"this sn no record",query_exit);
        ret = get_reccords_from_ipctable(E_QUERY_BY_TIME,ipc_info,p_query_result);
        if(p_query_result->durNum == 0){
            xeLOG_ERR("no record in %s/ipc.db ",ipc_info->storage_path);
        }else{
            // vector_iter iter;
            // vector_t *c = p_query_result->p_vector;
            // // STD_print("vector_empty:%ld %p",c->size,c);
            // c->tmp_cursor = 0;
            // for (iter = vector_begin(c); iter != vector_end(c); iter = vector_next(c)) {
            //     t_file_opt_info *tt = vector_iter_valuep(c, iter, t_file_opt_info);
            //     printf("vector--> file_name: %p dura:%d start :%d end :%d\n",
            //         &tt->file_des.file_name,
            //         tt->file_des.duration,
            //         tt->start_offset_sec,
            //         tt->end_offset_sec);
            // }
        }

    }else if (query_type == E_QUERY_IPCLIST){
        vector_t *p_query_vector  = vector_create(t_ipc_query_info);
        __check_return_point(p_query_vector,ret_flag,"malloc failed",query_exit);
        g_vector = p_query_vector;
        if(strcmp(collector_sn,"")){
            tiny_rec_query_sysmgntdb_ipclist(E_QUERY_IPCLIST_BY_GTSSN,
                collector_sn,(void *)p_query_vector);
        }else{
            tiny_rec_query_sysmgntdb_ipclist(E_QUERY_IPCLIST_ALL,NULL,(void *)p_query_vector);  
        }

    }
query_exit:
    query_http_respond(req,ret_flag,errReason,&queryinfo,g_vector);
    if(g_vector)
        vector_destroy(g_vector);
    if(root)
        cJSON_Delete(root);
    STD_print("query_info_setup out...");
}

typedef struct _deleteinfo{
    char          sid[HISOME_LEN_128];  
    char          ipc_SN[HISOME_LEN_128];
    char          ipc_MAC[HISOME_LEN_128];

    char          del_type[HISOME_LEN_64];
    char          _startTime[HISOME_LEN_128];
    char          _endTime[HISOME_LEN_128];

}t_deleteinfo;


int delete_http_respond(MyHttpPack* req,int get_fail,
    char *errReason,  t_deleteinfo *p_deleteinfo)
{
    cJSON *rsp,*rspHeader,*rspArr,*rspData;

    rsp=cJSON_CreateArray();
    rspHeader = cJSON_CreateObject();
    rspData = cJSON_CreateObject();

    cJSON_AddStringToObject(rspHeader,"method","DELETE");
    cJSON_AddStringToObject(rspHeader,"SID", p_deleteinfo->sid);
    cJSON_AddStringToObject(rspHeader,"SN", p_deleteinfo->ipc_SN);
    cJSON_AddItemToObject(rspHeader, "data", rspArr=cJSON_CreateArray());

    if(get_fail){
        cJSON_AddStringToObject(rspHeader,"result","FAIL");
        cJSON_AddStringToObject(rspData,"reason",errReason);
    }else{
        cJSON_AddStringToObject(rspHeader,"result","SUCCESS");
    }
    
    cJSON_AddItemToArray(rsp,rspHeader);
    cJSON_AddItemToArray(rspArr,rspData);

    com_httpPack(req->httpReq.nc,rsp);
    cJSON_Delete(rsp);
    
    return 0;
}



void delete_info_setup(void *data)
{
    cJSON *root;
    int ret_flag = 0;
    char errReason[HISOME_LEN_512]={'\0'};
    MyHttpPack* req =(MyHttpPack*)data;
    t_deleteinfo delete_info ={0};
    t_ipc_query_info ipc_info_temp= {0};
    t_ipc_query_result query_result_temp = {0};
    t_ipc_query_info *ipc_info = &ipc_info_temp;
    t_ipc_query_result *p_query_result = &query_result_temp;
    vector_t *g_vector = NULL;

    char mycmd[HISOME_LEN_512] = {'\0'};

    STD_print("");
    root=cJSON_Parse(req->httpReq.hm->body.p);
    if (!root) {
        sprintf(errReason,"客户端发送数据有误");
        ret_flag=1;
        PRTLOG_ERR("Error before: [%s]",cJSON_GetErrorPtr());
        goto delete_exit;
    }else{
        char value[HISOME_LEN_256];
        int userid = 0;
        __prase_cjson_string(value,ret_flag,"userID",delete_exit);
        sscanf(value,"%d",&userid);
        if(NULL ==apiUsrMgnt_findOn_LINEUser(userid)){
            xeLOG_ERR("error, %d not online",userid);
            ret_flag = 1;
            sprintf(errReason,"error, %d not online",userid);
            goto delete_exit;
        }
        __prase_cjson_string(value,ret_flag,"SID",delete_exit);
            strcpy(delete_info.sid,value);
        __prase_cjson_string(value,ret_flag,"SN",delete_exit);
            strcpy(delete_info.ipc_SN,value);
        __prase_cjson_string(value,ret_flag,"del_type",delete_exit);
            strcpy(delete_info.del_type,value);
        if(!strcmp(delete_info.del_type,"segment")){
            __prase_cjson_string(value,ret_flag,"startTime",delete_exit);
                strcpy(delete_info._startTime,value);
            __prase_cjson_string(value,ret_flag,"endTime",delete_exit);
                strcpy(delete_info._endTime,value);
        }
    }


    if(!strcmp(delete_info.del_type,"all")){
        strcpy(ipc_info->ipc_sn, delete_info.ipc_SN);
        tiny_rec_query_sysmgntdb_info(E_TBL_IPCMGNT,(void *)ipc_info);
        __check_return_cstring(ipc_info->storage_path,ret_flag,"this sn no record",delete_exit);
        STD_print("ipc_info->storage_path:%s ipc_info->harddisk_dir:%s",ipc_info->storage_path,ipc_info->harddisk_dir);
        tiny_rec_update_sysmgntdb_tbl(E_TBL_IPCMGNT,E_DELETE_RECORD,(void *)ipc_info);
        snprintf(mycmd, sizeof(mycmd)-1, "rm -rf %s", ipc_info->storage_path);
        system(mycmd);
        {
            t_space_query_info space_res = {0};
            strcpy(space_res.harddisk_dir,ipc_info->harddisk_dir);
            tiny_rec_query_sysmgntdb_info(E_TBL_SPACE,&space_res);
            if(space_res.dir_used > 0){
                space_res.dir_free++;
                space_res.dir_used--;
                tiny_rec_update_sysmgntdb_tbl(E_TBL_SPACE,E_UPDATE_RECORD,&space_res);
            }
        }
    }else if (!strcmp(delete_info.del_type,"segment")){
        memset(ipc_info, 0 ,sizeof(t_ipc_query_info));
        memset(p_query_result, 0 ,sizeof(t_ipc_query_result));
        p_query_result->p_vector = vector_create(t_file_opt_info);
        __check_return_point(p_query_result->p_vector,ret_flag,"malloc failed",delete_exit);
        g_vector = p_query_result->p_vector;

        strcpy(ipc_info->ipc_sn, delete_info.ipc_SN);
        ipc_info->start_time =  com_localTimeStr2Int(delete_info._startTime);
        ipc_info->end_time =  com_localTimeStr2Int(delete_info._endTime);

        tiny_rec_query_sysmgntdb_info(E_TBL_IPCMGNT,(void *)ipc_info);
        __check_return_cstring(ipc_info->storage_path,ret_flag,"this sn no record",delete_exit);
        get_reccords_from_ipctable(E_QUERY_BY_TIME,ipc_info,p_query_result);
        if(p_query_result->durNum == 0){
            xeLOG_ERR("no record in %s/ipc.db ",ipc_info->storage_path);
        }else{
            t_ipc_statis_des statis_des={0};
            vector_iter iter;
            vector_t *c = p_query_result->p_vector;
            // STD_print("vector_empty:%ld %p",c->size,c);
            c->tmp_cursor = 0;


            tiny_get_statistics_ipcdb(ipc_info->storage_path,&statis_des);
            for (iter = vector_begin(c); iter != vector_end(c); iter = vector_next(c)) {
                t_file_opt_info *tt = vector_iter_valuep(c, iter, t_file_opt_info);
                STD_print("vector--> file_name: %s",
                    tt->file_des.file_name);
                tiny_update_ipcdb(E_DELETE_RECORD,ipc_info->storage_path,&tt->file_des);
                remove(tt->file_des.file_name);
                remove(tt->file_des.detail_info_name);
                statis_des.total_space -= tt->file_des.file_space;
                statis_des.num_files--;
                tiny_update_ipcdb(E_UPDATE_STATIS,ipc_info->storage_path,&statis_des);
            }
            update_time_for_statis_and_sysmgnt(ipc_info,&statis_des);
        }
    }else{

    }

    
delete_exit:
    if(g_vector)
        vector_destroy(g_vector);
    delete_http_respond(req,ret_flag,errReason,&delete_info);

    if(root)
        cJSON_Delete(root);
}